package com.yenlien.traceyun.business.service;

import com.yenlien.traceyun.business.dao.UnitDao;
import com.yenlien.traceyun.business.entity.Unit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by LiuSha on 2020/6/16.
 */
@Service
public class UnitService {
    @Autowired
    private UnitDao unitDao;


    public Page<Unit> findByList(final Unit unit) {
        Pageable pageable = PageRequest.of(unit.getPage(), unit.getPageSize(), Sort.Direction.DESC, "createtime");
        return unitDao.findAll(new Specification<Unit>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<Unit> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> companyId = root.get("companyId");
                //构造查询条件
                List<Predicate> list = new ArrayList<>();
                if (!StringUtils.isEmpty(unit.getCompanyId())) {
                    list.add(cb.equal(companyId, unit.getCompanyId()));
                }
                Predicate[] predicate = new Predicate[list.size()];
                return cb.and(list.toArray(predicate));
            }
        }, pageable);
    }

    public List<Unit> findByAll(String companyId) {
        if (!StringUtils.isEmpty(companyId)) {
            return unitDao.findByCompanyId(companyId);
        }
        return unitDao.findAll();
    }

    public void save(Unit unit) {
        if (StringUtils.isEmpty(unitDao.findByNameAndCompanyId(unit.getName(), unit.getCompanyId()))) {
            unitDao.save(unit);
        }
    }

    public void update(Unit unit) {
        unitDao.save(unit);
    }

    public Unit findById(String id) {
        return unitDao.findById(id);
    }

    public void delete(String id) {
        unitDao.deleteById(id);
    }
}
